package com.alvin.abp.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alvin.abp.common.context.CurrentUserContext;
import com.alvin.abp.common.util.EncryptUtils;
import com.alvin.abp.domain.AlvinUser;
import com.alvin.abp.service.UserService;
/**   
 * 
 * @author <a href="mailto:rex2.mj@gmail.com">Leo Meng</a>
 * @date $Date: Mar 25, 2013 $
 */
@Controller
public class AuthController {
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	@Autowired
	private UserService userService;	
	
	@RequestMapping(value = "/login.htm", method = RequestMethod.GET)
	public String loginForm(ModelMap model) {
		AlvinUser user = new AlvinUser();
		model.addAttribute("user", user);
		return "login";
	}
	
	@RequestMapping(value = "/login.htm", method = RequestMethod.POST)
	public String login(@RequestParam("mobile") String mobile,
			ModelMap model, HttpServletRequest request) throws ServletException, IOException {

		String view = "user/reg";
		AlvinUser user = userService.loadUserBasicInfo(mobile);
		
		if(user != null){
			CurrentUserContext.setCurrentUser(user);
			view = "redirect:/home.htm";
		}
		
		return view;
	}
	
	@RequestMapping(value = "/auth.htm", method = RequestMethod.GET)
	public String authForm(ModelMap model) {
		AlvinUser user = new AlvinUser();
		model.addAttribute("user", user);
		return "customauth";
	}
	
	@RequestMapping(value = "/auth.htm", method = RequestMethod.POST)
	public void customauth(@RequestParam("mobile") String mobile, @RequestParam("password") String password, 
			ModelMap model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		AlvinUser user = userService.loadUserBasicInfo(mobile);
		
		if(user.getPassword().equals(EncryptUtils.encryptMD5(password))){
			CurrentUserContext.session().setAttribute(CurrentUserContext.AUTHED_USER, true);
			String uri = request.getRequestURI();
			request.getRequestDispatcher(uri).forward(request, response);
		}else{
			response.sendRedirect("home.htm");
		}
		
	}
	
	@RequestMapping(value = "/logout.htm", method = RequestMethod.GET)
	public String logout() {
		CurrentUserContext.invalidateUser();
		return "redirect:login.htm";
	}
	
}
